package com.xnyzc.lhy.task.fallback.driver;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.component.sms.AliCloudSMSUtils;
import com.xnyzc.lhy.common.constant.AliCloudSmsConstant;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.order.EOrderChannelType;
import com.xnyzc.lhy.common.penum.vehicle.ECallVehType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.mis.entity.manager.OaSysManager;
import com.xnyzc.lhy.mis.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.mis.entity.system.OaSysSendMessage;
import com.xnyzc.lhy.order.entity.gps.OaDVehicleGps;
import com.xnyzc.lhy.order.entity.user.OaDUser;
import com.xnyzc.lhy.task.fegin.driver.QuartzDriverEarlyWarningService;
import com.xnyzc.lhy.task.mapper.sys.OaCOrderPersonalMapper;
import com.xnyzc.lhy.task.mapper.sys.OaDUserMapper;
import com.xnyzc.lhy.task.mapper.sys.OaSysSendMessageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class QuartzDriverEarlyWarningServiceFallback implements QuartzDriverEarlyWarningService {
    @Autowired
    private RedisCommon redisCommon;
    @Autowired
    private OaCOrderPersonalMapper oaCOrderPersonalMapper;
    @Autowired
    private OaDUserMapper oaDUserMapper;
    @Autowired
    private OaSysSendMessageMapper oaSysSendMessageMapper;

    @Override
    public void driverEarlyWarning() {
        //控制是否发送短信
        Boolean isMSG = false;
        List oderStatusList = new ArrayList();
        oderStatusList.add(0,3);//司机已接单
        oderStatusList.add(1,4);//司机前往预约地点
        QueryWrapper<OaCOrderPersonal> personalQueryWrapper = new QueryWrapper<>();
        personalQueryWrapper.in(OaCOrderPersonal.ORDER_STATUS,oderStatusList);
        personalQueryWrapper.eq(OaCOrderPersonal.DELETED,0);
        List<OaCOrderPersonal> oaCOrderPersonalList = oaCOrderPersonalMapper.selectList(personalQueryWrapper);
        if(CheckUtil.objIsEmpty(oaCOrderPersonalList)){
            return ;
        }
        for (OaCOrderPersonal info: oaCOrderPersonalList) {
            String redisKey = RedisPrefixConstant.GPS_VEH_KEY_PREFIX + info.getDriverId();
            log.info("获取司机位置redisKey: " + redisKey);
            String string = redisCommon.getStr(redisKey);
            log.info("获取司机位置data: " + string);
            if (string == null) {
                continue;
            } else {
                long now = System.currentTimeMillis();
                long difTime = info.getAppointment().getTime() -now;
                OaDVehicleGps oaDVehicleGps = JSON.parseObject(string, OaDVehicleGps.class);
                //乘客的出发金纬度
                BigDecimal clng = new BigDecimal(info.getStartLng());
                BigDecimal clat = new BigDecimal(info.getStartLat());
                Double lon1 = clng.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
                Double lat1 = clat.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
                //司机的金纬度
                BigDecimal dlng = new BigDecimal(oaDVehicleGps.getLng());
                BigDecimal dlat = new BigDecimal(oaDVehicleGps.getLat());
                Double lon2 = dlng.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
                Double lat2 = dlat.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
                //距离计算 --返回米除以1000 转换公里
                Double differenceKilometre = getDistance( lon1, lat1, lon2, lat2)/1000;
                ///获取该城市的司管电话
                QueryWrapper<OaSysSendMessage> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq(OaSysSendMessage.OFFICE_ID, info.getOfficeId());
                OaSysSendMessage oaSysSendMessage = oaSysSendMessageMapper.selectOne(queryWrapper);
                //判断是否可以发送短信给该城市的司管
                if(CheckUtil.objIsNotEmpty(oaSysSendMessage) && oaSysSendMessage.getDriverOrderEarlyWarning()==1){
                    if(differenceKilometre >= 50 && difTime <= 1000*60*60*2){
                        //司机与出发地距离超过等于50公里，当前时间距离预约时间<=2小时;
                        isMSG = true;
                    }else if((differenceKilometre < 50 && differenceKilometre >= 30 ) && difTime <= 1000*60*60*1.5){
                        //50公里>司机与出发地距离>=30公里，当前时间距离预约时间<=1.5小时;
                        isMSG = true;
                    }else if ((differenceKilometre < 30 && differenceKilometre >= 20) && difTime <= 1000*60*60){
                        //30公里>司机与出发地距离>=20公里，当前时间距离预约时间<=1小时;
                        isMSG = true;
                    }else if ((differenceKilometre < 20 && differenceKilometre >= 10) && difTime <= 1000*60*40){
                        //20公里>司机与出发地距离>=10公里，当前时间距离预约时间<=40分钟;
                        isMSG = true;
                    }else if ((differenceKilometre < 10 && differenceKilometre >= 5) && difTime <= 1000*60*30){
                        //10公里>司机与出发地距离>=5公里，当前时间距离预约时间<=30分钟;
                        isMSG = true;
                    }
                    if(isMSG){
                        JSONObject json = new JSONObject();
                        String orderNo = info.getOrderNo();
                        int orderNoLength=orderNo.length();
                        json.put("orderId",orderNo);
                        if(orderNoLength > 20){
                            json.put("orderId",orderNo.substring(orderNoLength-20,orderNoLength));
                        }
                        json.put("channel", EOrderChannelType.findById(info.getOrderChannel()).getValue());
                        json.put("calltype", ECallVehType.finaByType(info.getOrderType()).getValue());
                        json.put("driver_name",null);
                        json.put("driver_phone",null);
                        OaDUser oaDUser = oaDUserMapper.selectById(info.getDriverId());
                        log.info("司机信息 ：" + JSONObject.toJSONString(oaDUser));
                        if(CheckUtil.objIsNotEmpty(oaDUser)){
                            json.put("driver_name",oaDUser.getDriverName());
                            json.put("driver_phone",oaDUser.getDriverPhone());
                        }
                        //从redi获取数据
                        String redisKey2 = RedisPrefixConstant.DRIVER_ORDER_MSG+orderNo;
                        String sendMessageList = redisCommon.getStr(redisKey2);
                        if(CheckUtil.strIsEmpty(sendMessageList)){
                            //数据为空 发送短信
                            AliCloudSMSUtils.sendMessage(oaSysSendMessage.getManagerPhone().toString(), AliCloudSmsConstant.DRIVER_IMPLEMENT_MSG, json);
                            redisCommon.set(redisKey2,"1", (long) (1000*60*60*2.5));
                            log.info("发送司管短信订单号:" + orderNo+" 成功。");
                        }else {//数据不为空 已经发送过
                            log.info("已发送司管短信订单号:" + orderNo);
                        }
                    }
                }else {
                    log.info("该供应商未配置司管电话:" + info.getOfficeId());
                }
            }
        }
    }
    /**
     * 距离计算，请参考下面代码
     * @param lng1
     * @param lat1
     * @param lng2
     * @param lat2
     * @return 米
     */
    public static double getDistance(double lng1,double lat1,double lng2,double lat2){
        double radLat1 = Math.toRadians(lat1);
        double radLat2 = Math.toRadians(lat2);
        double a = radLat1 - radLat2;
        double b = Math.toRadians(lng1) - Math.toRadians(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1)
                * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378137.0;// 取WGS84标准参考椭球中的地球长半径(单位:m)
        s = Math.round(s * 10000) / 10000;
        return s;
    }
}
